package com.bnzj.cloud.oauth2resource.config;

import com.bnzj.cloud.oauth2resource.custom.CustomOauth2AuthenticationEntryPoint;
import com.bnzj.cloud.oauth2resource.ext.OauthResourceHttpSecurityAdapter;
import com.bnzj.core.web.security.CustomAccessDeniedHandler;
import com.bnzj.core.web.security.CustomAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @ClassName Oauth2ResourceConfiguration
 * @Description oauth2 resource java config 配置
 * @Author
 * @Date 2020/2/19
 * @Version V1.0
 **/
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableWebSecurity
@Order(0)
public class Oauth2ResourceConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private OauthResourceHttpSecurityAdapter oauthResourceHttpSecurityAdapter;

    @Bean("defaultCustomOauth2AuthenticationEntryPoint")
    @ConditionalOnMissingBean(name = "customOauth2AuthenticationEntryPoint")
    public CustomOauth2AuthenticationEntryPoint customOauth2AuthenticationEntryPoint(){
        return new CustomOauth2AuthenticationEntryPoint();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public CustomAuthenticationEntryPoint customAuthenticationEntryPoint() {
        return new CustomAuthenticationEntryPoint();
    }

    @Bean
    @ConditionalOnMissingBean(name = "customAccessDeniedHandler")
    public CustomAccessDeniedHandler customAccessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        oauthResourceHttpSecurityAdapter.config(http);
    }

}
